<script lang="ts" setup>
import DescVue from '@/components/Desc.vue'
import _ from 'lodash'
import { ref, watchPostEffect } from 'vue'
import {
  def
} from './runtime'

const ns = 'PageEolinkCfg'
const getItem = (key: string, defaultVal = '') => localStorage.getItem(ns + key) || defaultVal
const setItem = (key: string, val = '') => localStorage.setItem(ns + key, val)


const DEFAULT_CODE =
  _.trim(`${def}`)
const inputValKey = 'inputVal'
// const inputValRef = ref(getItem(inputValKey, DEFAULT_CODE))
const inputValRef = ref(DEFAULT_CODE)

watchPostEffect(() => {
  setItem(inputValKey, inputValRef.value)
})

function handleDownloadBtnClick() {
  const a = document.createElement('a')
  a.href = URL.createObjectURL(new Blob([inputValRef.value], { type: 'text/plain' }))
  a.download = '配置文件.js'
  a.click()
}

function handleFileChange(e: any) {
  const reader = new FileReader()
  reader.onload = (evt => {
    const txt = evt.target?.result
    if (txt) {
      inputValRef.value = txt as string
    }
  })
  reader.readAsText(_.head(e.target.files) as any)
}

function reset() {
  inputValRef.value = DEFAULT_CODE
}
</script>

<script lang="ts">
export default {
  name: 'PageEolinkTemplate'
}
</script>
<template>
  <a-page-header title="配置模版" sub-title="只在/eo/list页面生效, 其他的页面如/eo/ws/**下的配置是固定的(不可修改)" @back="$router.back">
    <template #extra>
      <a-button type="link" @click="$router.push('/eo/exp')">查看说明</a-button>
      <a-button type="link" @click="handleDownloadBtnClick">下载</a-button>
      <a-button type="link" @click="reset">重置默认值</a-button>
    </template>
  </a-page-header>
  <div class="wrapper">
    <a-textarea v-model:value="inputValRef" placeholder="请输入代码"></a-textarea>
    <desc-vue class="code" :code="inputValRef"></desc-vue>
  </div>
  <a-input accept=".js" type="file" @change="handleFileChange"></a-input>
</template>
<style lang="less" scoped>
.wrapper {
  height: 80vh;
  width: 80vw;
  overflow: auto;
  display: flex;
  justify-content: space-between;

  >* {
    width: 100%;
    min-width: 50%;
  }

  .ant-input {
    margin-bottom: 24px;
  }


  .code {
    display: flex;

    pre {
      border: 10px solid red;
    }

    width: 100%;
    height: auto;
  }
}
</style>